class Solution { //每次找最大值都需要克隆，排序，超出时间限制
    public int[] maxSlidingWindow(int[] nums, int k) {
        if(k >= nums.length) {
            Arrays.sort(nums);
            int[] aa = new int[1];
            aa[0] = nums[nums.length - 1];
            return aa;
        }
        int length = nums.length;
        int[] ans = new int[length - k + 1];
        int[] aa = new int[k];
        int ansi = 0;

        for(int i = 0;i < k;i++) {
            aa[i] = nums[i];
        } 
        for(int i = k;i <= length;i++) {
            int[] bb = aa.clone();
            Arrays.sort(bb);
            ans[ansi] = bb[k - 1];
            if(i == length) {
                break;
            }
            aa[i%k] = nums[i];
            ansi++;
        }
        return ans;
    }
}

class Solution { //每次找最大值都需要克隆，排序，超出时间限制
    public int[] maxSlidingWindow(int[] nums, int k) {
        int n = nums.length;
        Deque<Integer> deque = new LinkedList<Integer>();
        for (int i = 0; i < k; ++i) {
            while (!deque.isEmpty() && nums[i] >= nums[deque.peekLast()]) {
                deque.pollLast();
            }
            deque.offerLast(i);
        }

        int[] ans = new int[n - k + 1];
        ans[0] = nums[deque.peekFirst()];
        for (int i = k; i < n; ++i) {
            while (!deque.isEmpty() && nums[i] >= nums[deque.peekLast()]) {
                deque.pollLast();
            }
            deque.offerLast(i);
            while (deque.peekFirst() <= i - k) { //判断第一个下标是否还在滑动窗口中，不在弹出
                deque.pollFirst();
            }
            ans[i - k + 1] = nums[deque.peekFirst()];
        }
        return ans;
    }
}